import {ethers} from "ethers";
import { ref } from "vue";
import {useUserInfoStore} from "@/stores/userInfo"
import { chainId} from "@/utils/config";
let provider, signer, accounts, balance
const switchNetwork = async (chain) => {
  try {
    var gasHex = ethers.utils.hexValue(chainId)
    if (chain && (gasHex == chain)) {
      return
    }
    await window.ethereum.request({
      "method": "wallet_switchEthereumChain",
      "params": [{
        "chainId": gasHex
      }]
    });
    window.location.reload()
    return
  } catch (error) {

  }
}
const eth = {
  async getAccount() {
    try {
      const userInfo = useUserInfoStore();
      let address = ''
      if (userInfo.address) {
        address = store.state.address.toLowerCase()
      } else {
        provider = new ethers.providers.Web3Provider(window.ethereum)
        accounts = await provider.send("eth_requestAccounts", []);
        address = accounts[0].toLowerCase()
        userInfo.changeAddress(address);
      }
      return address 
    } catch (error) {
      
    }

  },
  async linkWallet() {
    const userInfo = useUserInfoStore();
    try {
      provider = await new ethers.providers.Web3Provider(window.ethereum);
      let network = await provider.getNetwork();
      if (parseInt(network.chainId) != chainId) {
        switchNetwork();
        return;
      }
      signer = await provider.getSigner();
      accounts = await provider.send("eth_requestAccounts", []);
      let address = accounts[0];
      userInfo.changeAddress(address);
      balance = await provider.getBalance(address);
      balance = parseFloat(ethers.utils.formatUnits(balance._hex, 18)).toFixed(
        4
      );
    } catch (err) {
      console.log(err);
    }
  },
  // async getBalance(provider, address) {
  //   balance = await provider.getBalance(address);
  //   store.commit("BALANCE", balance);
  // },
};
export {
  switchNetwork,
}
// mouse.js
export default eth